package com.example.quce.controller;

import cn.hutool.core.util.StrUtil;
import com.example.quce.bo.LoginBO;
import com.example.quce.common.R;
import com.example.quce.entity.Classify;
import com.example.quce.entity.User;
import com.example.quce.mapper.ClassifyMapper;
import com.example.quce.mapper.UserMapper;
import com.example.quce.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {


    @Autowired(required=false)
    UserMapper userMapper;

    private final ClassifyMapper classifyMapper;

    private final IUserService userService;

    @GetMapping("/all")
    public R getAll() {
        return R.ok(userService.lambdaQuery().list());
    }


    @PostMapping("/login1")
    public R login1(@RequestBody LoginBO request) {
        System.out.println("调用login1");
        User foundUser = userMapper.selectUserByMP(request.getMobile(), request.getPassword());
        return R.ok(foundUser);
    }

    //注销用户
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable int id){
        int re=userMapper.deleteUserById(id);
        return R.ok(re);
    }

    @PostMapping("/register")
    public R register(@RequestBody User request) {
        System.out.println("调用register");
        // 检查手机号是否已被注册
        User existingUser = userMapper.selectUserByMobile(request.getMobile());
        if (existingUser != null) {
            return R.error("手机号已经被注册");
        }
        // 注册成功，插入新用户
        userMapper.insertUser(request);
        return R.ok("注册成功");
    }


    @PostMapping("/update")
    public R updateUserInfo(@RequestBody User request) {
        System.out.println("调用updateUserInfo");
        User user = userMapper.selectUserByMobile(request.getMobile());
        if (user == null) {
            return R.error("用户不存在");
        }

        if (StrUtil.isNotEmpty(request.getPassword())) {
            user.setPassword(request.getPassword());
        }

        if (StrUtil.isNotEmpty(request.getEmail())) {
            user.setEmail(request.getEmail());
        }

        if (StrUtil.isNotEmpty(request.getNickname())) {
            user.setEmail(request.getNickname());
        }

        if (request.getBirthday() != null) {
            user.setBirthday(request.getBirthday());
        }

        // 更新用户信息
        userMapper.updateUserInfo(user);
        return R.ok("更新成功");
    }


    //根据分类名称查询发现标签的详细测试名
    // http://localhost:8080/api/user/classifyInfo
    @PostMapping("/classifyInfo")
    public R classifyInfo(@RequestBody Classify request){
        System.out.println("调用classifyInfo");
        List<String> selectClassifyInfo = classifyMapper.selectClassifyByName(request.getCname());
        return R.ok(selectClassifyInfo);
    }
}
